package com.github.catvod.spider;


import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.AESEncryption;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.Util;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 腐剧TV看剧
 * @author fs
 * 网站:https://www.80share.com/
 */
public class FuJvTv extends Spider {
    private String siteUrl = "https://www.80share.com/";
    private String searchUrl=siteUrl+"vodsearch/";
    private String detailUrl=siteUrl+"movie/";
    private String categoryUrl=siteUrl+"type/";
    private String playUrl="https://jiexi.35cdn.com/player/ec.php";

    // AES加密

    // 向量偏移固定
    private String iv="2F131BE91247866E";


    @Override
    public String homeContent(boolean filter) throws Exception {
        List<com.github.catvod.bean.Class> classes = new ArrayList<>();
        String[] typeIdList = {"/", "dianying.html", "lianxuju.html", "zongyi.html", "dongman.html"};
        String[] typeNameList = {"首页", "电影", "连续剧", "综艺", "动漫"};
        for (int i = 0; i < typeNameList.length; i++) {
            classes.add(new Class(typeIdList[i], typeNameList[i]));
        }
        return Result.string(classes, new ArrayList<>());
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (tid.equals("/")){
            // 首页
            Document doc = Jsoup.parse(OkHttp.string(siteUrl, getHeaders()));
            List<Vod> list=parseCatagoryHtmlVod(doc);
            return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
        }
        Document doc = Jsoup.parse(OkHttp.string(categoryUrl.concat(tid), getHeaders()));
        List<Vod> list=parseCatagoryHtmlVod(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
    }

    private List<Vod> parseCatagoryHtmlVod(Document doc) {
        List<Vod> list = new ArrayList<>();
        Elements liList = doc.select("ul.myui-vodlist.clearfix > li");
        for (Element li : liList) {
            Vod vod = new Vod();
            String pic = li.select("a").attr("data-original");
            vod.setVodPic(pic);
            vod.setVodName(li.select("a").attr("title"));
            vod.setVodId(li.select("a").attr("href").split("/")[2]);
            vod.setVodRemarks(li.select("span.pic-text.text-right").text());
            list.add(vod);
        }
        return list;
    }


    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        System.out.println("ddd");
        @SuppressLint("DefaultLocale") String url = searchUrl.concat(URLEncoder.encode(key)).concat(String.format("----------1---.html"));
        Document doc = Jsoup.parse(OkHttp.string(url, getHeaders()));
        List<Vod> list=parseHtmlVod(doc);
        return Result.string(list);
    }

    private List<Vod> parseHtmlVod(Document doc) {
        List<Vod> list = new ArrayList<>();
        Elements liList = doc.select("ul.clearfix > li.clearfix");
        for (Element li : liList) {
            Vod vod = new Vod();
            String pic = li.select("a").attr("data-original");
            vod.setVodPic(pic);
            vod.setVodName(li.select("a").attr("title"));
            vod.setVodId(li.select("a").attr("href").split("/")[2]);
            vod.setVodRemarks(li.select("span.pic-text").text());
            list.add(vod);
        }
        return list;
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        Document doc = Jsoup.parse(OkHttp.string(detailUrl.concat(ids.get(0)), getHeaders()));
        String title = doc.select("h1.title").text();
        String desc = doc.select("#desc").text();
        String pic = doc.select("a.picture > img").attr("data-original");
        String category = doc.select("p.data").get(0).select("a").get(0).text();
        String area = doc.select("p.data").get(0).select("a").get(1).text();
        String year = doc.select("p.data").get(0).select("a").get(2).text();
        String remark = doc.select("p.data").get(1).text().replace("更新：","");
        String actor = doc.select("p.data").get(2).text().replace("主演：","");
        String deirector = doc.select("p.data").get(3).text().replace("导演：","");
        String[] links = Objects.requireNonNull(doc.select("ul.nav-tabs").first()).text().split(" ");
        Elements playList = doc.select("ul.myui-content__list");
        List<String> vod_play_url = new ArrayList<>();
        for (Element play : playList) {
            Elements playlink = play.select("li");
            StringBuilder stringBuilder = new StringBuilder();
            for (Element link : playlink) {
                String playName = link.select("a").text();
                String playUrl = link.select("a").attr("href");
                // 如果是最后一个元素不加#号
                if (playlink.get(playlink.size() - 1).equals(link)){
                    stringBuilder.append(playName).append("$").append(playUrl);
                }else {
                    stringBuilder.append(playName).append("$").append(playUrl).append("#");
                }
            }
            vod_play_url.add(stringBuilder.toString());
        }
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodPic(pic);
        vod.setVodName(title);
        vod.setVodPic(pic);
        vod.setVodRemarks(remark);
        vod.setVodPlayFrom(TextUtils.join("$$$", links));
        vod.setVodPlayUrl(TextUtils.join("$$$", vod_play_url));
        vod.setVodYear(year);
        vod.setVodArea(area);
        vod.setVodActor(actor);
        vod.setVodDirector(deirector);
        vod.setVodContent(desc);
        vod.setTypeName(category);
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        String html = OkHttp.string(Util.removeUrlTrailingSlash(siteUrl).concat(id), getHeaders());
        String result = Util.findByRegex("var player_aaaa=(.*)</script>", html, 1);
        JSONObject jsonObject = Json.parseJson(result);
        String url = jsonObject.getString("url");
        String from = jsonObject.getString("from");
        HashMap<String, String> params = new HashMap<>();
        params.put("code","bt");
        params.put("url",url);
        params.put("from",from);
        params.put("if","1");
        String play_result = OkHttp.string(playUrl, params, getHeaders());
        String play_reuslt_json = Util.findByRegex("<script>let ConFig = (.*),box", play_result, 1);
        String playURl_encode = Json.parseJson(play_reuslt_json).getString("url");
        String uid = Json.parseJson(play_reuslt_json).getJSONObject("config").getString("uid");
        // 进行拼接密钥
        String key="2890"+uid+"tB959C";
        // 进行解密
        String m3u8 = AESEncryption.decrypt(playURl_encode, key, iv, AESEncryption.CBC_PKCS_7_PADDING);
        System.out.println(m3u8);
        return Result.get().url(m3u8).header(getHeaders()).string();
    }

    @Override
    public String searchContent(String key, boolean quick, String pg) throws Exception {
        System.out.println("ddd");
        @SuppressLint("DefaultLocale") String url = searchUrl.concat(URLEncoder.encode(key)).concat(String.format("----------%s---.html",pg));
        System.out.println(url);
        Document doc = Jsoup.parse(OkHttp.string(url, getHeaders()));
        System.out.println(doc);
        return super.searchContent(key, quick, pg);
    }

    private Map<String, String> getHeaders() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        return header;
    }
}
